import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Demo32 {

    public static void main(String[] args) throws InterruptedException {
        Hashtable<String, Integer> table = new Hashtable<>();
        table.put("key", 9);
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 模拟10个线程同时尝试操作同一个key
        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                // 这是非原子操作组合
                if (table.get("key") < 10) {
                    try {
                        // 加入短暂的休眠，让问题更容易复现
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    table.put("key", table.get("key") + 1);
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);

        //理想状态下table中key对应的value为10,但是因为线程并发操作，结果可能不是10
        System.out.println("最终Hashtable的内容: " + table);
    }
}
